package com.roncoo.education.course.service.api.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.roncoo.education.course.common.bo.CourseInfoPageBO;
import com.roncoo.education.course.common.bo.CourseInfoSearchBO;
import com.roncoo.education.course.common.bo.CourseListByTagAndCategoryBO;
import com.roncoo.education.course.common.bo.CourseVideoBO;
import com.roncoo.education.course.common.dto.*;
import com.roncoo.education.course.service.dao.*;
import com.roncoo.education.course.service.dao.impl.mapper.entity.*;
import com.roncoo.education.course.service.dao.service.UserCourseAppointmentService;
import com.roncoo.education.user.feign.interfaces.IFeignLecturer;
import com.roncoo.education.user.feign.vo.LecturerVO;
import com.roncoo.education.util.base.Result;
import com.roncoo.education.util.enums.IsPutawayEnum;
import com.roncoo.education.util.enums.StatusIdEnum;
import com.roncoo.education.util.field.BOField;
import com.roncoo.education.util.tools.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 课程信息
 *
 * @author wujing
 */
@Component
public class ApiCourseBiz {

	@Autowired
	private CourseDao courseDao;
	@Autowired
	private CourseIntroduceDao courseIntroduceDao;
	@Autowired
	private CourseChapterDao courseChapterDao;
	@Autowired
	private CourseChapterPeriodDao courseChapterPeriodDao;
	@Autowired
	private IFeignLecturer bossLecturer;
	@Autowired
	private CourseAuditDao courseAuditDao;

	@Autowired
	private UserCourseAppointmentService userCourseAppointmentService;

//	@Autowired(required = false)
//	private ElasticsearchTemplate elasticsearchTemplate;

//	@Autowired
//	private ResultMapperExt resultMapperExt;

	/**
	 * 课程详情接口
	 *
	 * @param courseView
	 * @return
	 */
	public Result<CourseViewDTO> view(CourseVideoBO courseVideoBO) {
		if (courseVideoBO.getCourseId() == null) {
			return Result.error("课程ID不能为空");
		}
		// 课程信息
		Course course = courseDao.getById(courseVideoBO.getCourseId());
		if (course == null) {
			return Result.error("找不到该课程信息");
		}
		CourseViewDTO data = BeanUtil.copyProperties(course, CourseViewDTO.class);

		// 课程介绍
		CourseIntroduce courseIntroduce = courseIntroduceDao.getById(data.getIntroduceId());
		if (!StringUtils.isEmpty(courseIntroduce)) {
			data.setIntroduce(BeanUtil.copyProperties(courseIntroduce, CourseIntroduceDTO.class).getIntroduce());
		}

		// 讲师信息
		LecturerVO lecturerVO = bossLecturer.getByLecturerUserNo(data.getLecturerUserNo());
		if (StringUtils.isEmpty(lecturerVO)) {
			return Result.error("根据讲师用户编号没找到对应的讲师信息!");
		}
		data.setLecturer(BeanUtil.copyProperties(lecturerVO, LecturerDTO.class));

		// 章节信息
		List<CourseChapter> courseChapterList = courseChapterDao.listByCourseIdAndStatusId(courseVideoBO.getCourseId(), StatusIdEnum.YES.getCode());
		if (CollectionUtil.isNotEmpty(courseChapterList)) {

			List<CourseChapterDTO> courseChapterDTOS = BeanUtil.copyProperties(courseChapterList, CourseChapterDTO.class);
			data.setChapterList(courseChapterDTOS);
		}

		// 课时信息
		if (CollectionUtil.isNotEmpty(data.getChapterList())) {
			for (CourseChapterDTO courseChapterDTO : data.getChapterList()) {
				List<CourseChapterPeriod> courseChapterPeriodList = courseChapterPeriodDao.listByChapterIdAndStatusId(courseChapterDTO.getId(), StatusIdEnum.YES.getCode());

				List<CourseChapterPeriodDTO> CourseChapterPeriodDTOs = BeanUtil.copyProperties(courseChapterPeriodList, CourseChapterPeriodDTO.class);
				courseChapterDTO.setPeriodList(CourseChapterPeriodDTOs);
			}
		}

		//未开课时，查询预约报名人数
		if (data.getIsOpen() == 0) {
			int count = userCourseAppointmentService.count(Wrappers.<UserCourseAppointment>lambdaQuery().eq(UserCourseAppointment::getCourseId, courseVideoBO.getCourseId()));
			data.setCountAppointment(count);
		}

		return Result.success(data);
	}

	/**
	 * 课程信息列表接口
	 *
	 * @param courseInfoPageBO
	 * @return
	 * @author wuyun
	 */
	public Result<Page<CourseInfoPageDTO>> list(CourseInfoPageBO courseInfoPageBO) {

		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(BOField.STATUS_ID,StatusIdEnum.YES.getCode());
		queryWrapper.eq(BOField.IS_PUTAWAY,IsPutawayEnum.YES.getCode());
		queryWrapper.eq(!StringUtils.isEmpty(courseInfoPageBO.getCategoryId1()),BOField.CATEGORY_ID1,courseInfoPageBO.getCategoryId1());
		queryWrapper.eq(!StringUtils.isEmpty(courseInfoPageBO.getCategoryId2()),BOField.CATEGORY_ID2,courseInfoPageBO.getCategoryId2());
		queryWrapper.eq(!StringUtils.isEmpty(courseInfoPageBO.getCategoryId3()),BOField.CATEGORY_ID3,courseInfoPageBO.getCategoryId3());
		queryWrapper.eq(!StringUtils.isEmpty(courseInfoPageBO.getIsFree()),BOField.IS_FREE,courseInfoPageBO.getIsFree());
		queryWrapper.like(!StringUtils.isEmpty(courseInfoPageBO.getCourseName()),BOField.COURSE_NAME,courseInfoPageBO.getCourseName());
		queryWrapper.orderByDesc("sort,id");
		Page<Course> coursePage = courseDao.listForPage(courseInfoPageBO.getPageCurrent(), courseInfoPageBO.getPageSize(), queryWrapper);
		Page<CourseInfoPageDTO> courseInfoPageDTOPage = new Page<>();
		BeanUtils.copyProperties(coursePage,courseInfoPageDTOPage);
		return Result.success(courseInfoPageDTOPage);
	}

	/**
	 * 课程搜索列表接口
	 * @param bo
	 * @return
	 */
	public Result<Page<CourseInfoSearchPageDTO>> searchList(CourseInfoSearchBO bo) {
		QueryWrapper<Course> wrapper = new QueryWrapper<>();
		wrapper.eq(BOField.STATUS_ID,StatusIdEnum.YES.getCode());
		wrapper.eq(BOField.IS_PUTAWAY,IsPutawayEnum.YES.getCode());
		wrapper.like(!StringUtils.isEmpty(bo.getCourseName()),BOField.COURSE_NAME,bo.getCourseName());

		Page<Course> coursePage = courseDao.listForPage(bo.getPageCurrent(), bo.getPageSize(), wrapper);
		Page<CourseInfoSearchPageDTO> courseInfoSearchPageDTOPage = new Page<>();
		BeanUtils.copyProperties(coursePage,courseInfoSearchPageDTOPage);

		return Result.success(courseInfoSearchPageDTOPage);
	}

	/**
	 * 通过标签和分类查询课程列表
	 * @param courseBO
	 * @return
	 */
	public Result<CourseListByTagAndCategoryDTO> listByTagAndCategory(CourseListByTagAndCategoryBO courseBO) {
		//如果标签不为空
		List<CourseAudit> courses;
		if (courseBO.getTagId() != null) {
			courses = courseAuditDao.listByTag(courseBO);
		} else {//如果标签为空，按分类查询课程
			QueryWrapper<CourseAudit> wrapper = new QueryWrapper<>();
			//如果要查询全部
			if (!courseBO.isAllCateGory()) {
				wrapper.eq(BOField.CATEGORY_ID1, courseBO.getCategoryId());
			}
			wrapper.eq(BOField.STATUS_ID, StatusIdEnum.YES.getCode());
			wrapper.eq(BOField.IS_PUTAWAY, IsPutawayEnum.YES.getCode());
			courses = courseAuditDao.list(wrapper);
		}
		return Result.success(new CourseListByTagAndCategoryDTO().setCourseDTOList(courses));
	}

	/**
	 * TODO 根据标签展示
	 */
	public Result<Page<CourseInfoSearchPageDTO>> searchListByTag(){
		return null;
	}

	/**
	 * 课程搜索列表接口 es搜索 暂时不用
	 *
	 * @param courseInfoSearchBO
	 * @author wuyun
	 */
	/*
	public Result<Page<CourseInfoSearchPageDTO>> searchList(CourseInfoSearchBO bo) {
		if (StringUtils.isEmpty(bo.getOrgNo())) {
			return Result.error("orgNo不能为空");
		}
		if (bo.getPageCurrent() <= 0) {
			bo.setPageCurrent(1);
		}
		if (bo.getPageSize() <= 0) {
			bo.setPageSize(20);
		}

		if (StringUtils.isEmpty(bo.getCourseName())) {
			return Result.success(new Page<CourseInfoSearchPageDTO>());
		}

		String heightField = "courseName";

		Field hfield = null;
		if (bo.getIsHfield() != null && bo.getIsHfield().equals(IsHfield.YES.getCode())) {
			hfield = new HighlightBuilder.Field(heightField).preTags("<mark>").postTags("</mark>");
		}

		NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder();
		if (bo.getIsHfield() != null && bo.getIsHfield().equals(IsHfield.YES.getCode())) {
			nsb.withHighlightFields(hfield);// 高亮字段
		}
		nsb.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));// 评分排序（_source）
		nsb.withSort(new FieldSortBuilder("courseSort").order(SortOrder.DESC));// 课程排序（courseSort）
		nsb.withPageable(PageRequest.of(bo.getPageCurrent() - 1, bo.getPageSize()));
		// 复合查询，外套boolQuery
		BoolQueryBuilder qb = QueryBuilders.boolQuery();
		// 精确查询termQuery不分词，must参数等价于AND
		qb.must(QueryBuilders.termQuery("orgNo", bo.getOrgNo()));
		// 模糊查询multiMatchQuery，最佳字段best_fields
		qb.must(QueryBuilders.multiMatchQuery(bo.getCourseName(), "courseName", "lecturerName").type(MultiMatchQueryBuilder.Type.BEST_FIELDS));

		nsb.withQuery(qb);

		org.springframework.data.domain.Page<EsCourse> page = elasticsearchTemplate.queryForPage(nsb.build(), EsCourse.class, resultMapperExt);
		return Result.success(EsPageUtil.transform(page, CourseInfoSearchPageDTO.class));
	}
	*/

}
